from django.contrib import auth
# Create your views here.
from django.contrib.auth import authenticate
from django.http import JsonResponse
from django.shortcuts import render
from my_shop import settings


# 返回登录页面
def login(request):
    return render(request, 'login.html')


# ajax登录
def ajax_login(request):
    json_dict = {}
    # 获取post请求提交的数据
    username = request.POST.get('username')
    password = request.POST.get('password')
    user = authenticate(username=username, password=password)

    if user:
        auth.login(request, user)  # 登录
        json_dict["status"] = 1000
        json_dict["msg"] = "登录成功"
        print(json_dict)
        request.session["info"] = {"username": user.username, "id": user.id, "password": user.password}
        request.session["csrf_token"] = {"csrf_token": settings.SECRET_KEY}
        request.session.set_expiry(60 * 60 * 24 * 7)  # 设置session过期时间
    else:
        json_dict["status"] = 1001
        json_dict["msg"] = "用户名或密码错误"
        print(json_dict)
    return JsonResponse(json_dict)


# 返回首页
def index(request):
    return render(request, 'index.html')


# 退出登录
def logout(request):
    auth.logout(request)
    return render(request, 'login.html')


# 用户管理
def user_management(request):
    return render(request, 'user_management.html')
